package com.sskj.hangqing.presenter;

import com.google.gson.Gson;
import com.sskj.common.base.HttpData;
import com.sskj.common.http.WebSocketObserver;
import com.sskj.common.util.DisposUtil;
import com.sskj.hangqing.ui.fragment.DepthFragment;
import com.sskj.lib.bean.WSFiveBean;
import com.sskj.lib.http.CallBackOption;
import com.sskj.lib.util.CommonUtil;

import java.util.concurrent.TimeUnit;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;


public class DepthFragmentPresenter extends BasePresenter<DepthFragment> {

    private WebSocketObserver stockSocket;
    private Disposable stockDisposable;

    public void getData(String code) {
        httpService.getDeepData(code)
                .execute(new CallBackOption<HttpData<WSFiveBean>>() {
                }.unLoadBind(mView)
                        .execute(httpData -> mView.updateUI(httpData.getData())));
    }

    public void initSocket(String code,boolean isBibi) {
        if (code == null)
            return;
        code = CommonUtil.dealReuqestCode(code);
        if (stockSocket == null) {
            stockSocket = httpService.pushCoinFiveDeep(code,isBibi);
            stockDisposable = stockSocket
                    .toObservable()
                    .throttleFirst(1, TimeUnit.SECONDS)
                    .map(s -> new Gson().fromJson(s, WSFiveBean.class))
                    .subscribeOn(Schedulers.newThread())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(data -> mView.updateUI(data), e -> {

                    });
        } else {
            if (isBibi) {
                stockSocket.send("{\"type\":\"depth_list\",\"list\":[\"" + code + "\"]}");
            }else {
                stockSocket.send("{\"type\":\"depth_list_lever\",\"list\":[\"" + code + "\"]}");
            }
        }
    }
    @Override
    public void detachView() {
        closeWebSocket();
        super.detachView();
    }

    public void closeWebSocket() {
        if (stockSocket!=null) {
            stockSocket.close();
            stockSocket = null;
        }
        DisposUtil.close(stockDisposable);

    }

}
